package com.bonc.modules.rpt.controller;

import cn.hutool.core.util.ObjectUtil;
import com.bonc.common.utils.Result;
import com.bonc.common.utils.SftpUtils;
import com.bonc.modules.rpt.service.ArcInfoAudioService;
import com.jcraft.jsch.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/rpt/arc")
public class ArcInfoAudioController {

    @Autowired
    private ArcInfoAudioService arcInfoAudioService;

    /** SFTP 登录用户名*/
    @Value("${audio.sftp.username}")
    private String sftpUsername;

    /** SFTP 登录密码*/
    @Value("${audio.sftp.password}")
    private String sftpPassword;

    /** SFTP 服务器地址IP地址*/
    @Value("${audio.sftp.host}")
    private String sftpHost;

    /** SFTP 端口*/
    @Value("${audio.sftp.port}")
    private String sftpPort;

    /** SFTP 音频保存路径*/
    @Value("${audio.sftp.audioDir}")
    private String sftpAudioDir;

    /** SFTP 音频保存路径*/
    @Value("${audio.sftp.filenameEncode}")
    private String sftpFilenameEncode;

    /**
     * 获取投诉音频
     * @param caseNo
     * @return
     */
    @GetMapping("/getAudioList/{caseNo}")
    @ResponseBody
    public Result getAudioList(@PathVariable("caseNo") String caseNo) {
        return Result.ok().put("data", arcInfoAudioService.queryData(caseNo));
    }


    /**
     * 获取投诉音频
     * @param audioPath
     * @param response
     * @return
     */
    @GetMapping("/playAudio")
    @ResponseBody
    public void playAudio(String audioPath, HttpServletRequest request, HttpServletResponse response) {
        if(ObjectUtil.isEmpty(audioPath)){
            return;
        }
        ChannelSftp channelSftp = null;
        Session session = null;
        try {
            session = SftpUtils.getSftpSession(sftpHost, Integer.valueOf(sftpPort), sftpUsername,  sftpPassword);
            if(session != null){
                channelSftp = SftpUtils.getChannelSftp(session);
            }
            if(channelSftp != null){
                if(ObjectUtil.isNotEmpty(sftpFilenameEncode)) {
                    channelSftp.setFilenameEncoding(sftpFilenameEncode);
                }
                SftpATTRS sftpATTRS = channelSftp.stat(audioPath);
                String rangeString = request.getHeader("Range");
                long rangeStart = Long.parseLong(rangeString.substring(rangeString.indexOf("=") + 1, rangeString.indexOf("-")));
                long rangeEnd = sftpATTRS.getSize() - 1;
                if (rangeString.indexOf("-") < rangeString.length() - 1) {
                    rangeEnd = Long.parseLong(rangeString.substring(rangeString.indexOf("-") + 1));
                }
                if (rangeStart == 0) {
                    response.setHeader("Content-Length", String.valueOf(sftpATTRS.getSize()));
                } else {
                    response.setStatus(HttpStatus.PARTIAL_CONTENT.value());
                    response.setHeader("Content-Length", (rangeEnd - rangeStart + 1) + "");
                }

                response.setHeader("Content-Type", "audio/mp3");
                response.setHeader("Content-Range", "bytes " + rangeStart + "-" + rangeEnd + "/" + String.valueOf(sftpATTRS.getSize()));
                response.setHeader("Accept-Ranges", "bytes");
                response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(audioPath, "UTF-8"));

                ServletOutputStream out = response.getOutputStream();
                channelSftp.get(audioPath, out, (SftpProgressMonitor)null, 0, rangeStart);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            if(channelSftp != null){
                channelSftp.disconnect();
            }
            if(session != null){
                session.disconnect();
            }
        }
    }
}
